package com.atguigu.yygh.order.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author 杨林
 * @create 2022-11-18 23:15 星期五
 * description:
 */
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    /**
     * 下单，生成支付二维码
     */
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId) {
        Map map = weixinService.createNative(orderId);
        return R.ok().data(map);
    }


    @Autowired
    private PaymentService paymentService;

    /**
     * 调用微信端接口查询订单状态
     * @param orderId
     * @return
     */
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable("orderId") Long orderId) {

        //调用查询接口
        Map<String,String> resultMap = weixinService.queryPayStatus(orderId);

        if (resultMap == null){
            return R.error().message("支付失败");
        }

        //支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            String out_trade_no = resultMap.get("out_trade_no");
            //支付成功  修改支付状态
            paymentService.paySuccess(out_trade_no,resultMap);
            return R.ok().message("支付成功");
        }

        return R.ok().message("支付中");
    }


}
